package com.bluewap.telco;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.apache.log4j.Logger;

import com.bluewap.core.AESGenerator;
import com.bluewap.core.Configuration;
import com.bluewap.core.Util;

public class VivasAdapter {
	private static Logger log = Logger.getLogger("vivas");
	
	public static String getToken (String transactionId, String price , String contentId){
		Configuration conf = Configuration.getInstance();
		String token = "";
		String postURL = "http://m.vmobile.vn/privateAPI/request";
		String cpId = "35";
		String key = "1AHb6FH44e881eBB";
		String param = "";
		try {
			Properties prop = conf.loadFile("vivas.properties");
			postURL = prop.getProperty("REQUESTURL");
			cpId = prop.getProperty("CPID");
			key = prop.getProperty("ENCRYPTKEY");
		} catch (Exception e) {
			log.error("Error", e);
		}

		param = "transactionId="+transactionId+"&price="+price+"&contentId="+contentId;
		param = AESGenerator.encrypt(param, key);
		List<String[]> parameters = new ArrayList<String[]>();
		String[] item = {"cpId", cpId};
		String[] item1 = {"param", param };
		parameters.add(item);
		parameters.add(item1);
		try {
			token =  Util.excuteProcessGET(parameters, postURL);
			log.debug("token=" + token + "|cpId = " + cpId + "|param =" + param);
		} catch (Exception e) {
			log.error("Error", e);
		}
		if (token.startsWith("0"))
			token =token.split("\\|")[1];
		else 
			token = null;
		return token;
	}
	
	public static String buildChargeLink(String token, String transactionId,String price, String contentType , String contentId){
		String link = "";
		String password = "";
		String redirectUrl = "";
		String cpId = "";
		String param = "";
		String key = "";
		Configuration conf = Configuration.getInstance();
		try {
			Properties prop = conf.loadFile("vivas.properties");
			password = prop.getProperty("PASSWORD");
			redirectUrl = prop.getProperty("RETURNURL");
			cpId = prop.getProperty("CPID");
			key = prop.getProperty("ENCRYPTKEY");
			
			password = AESGenerator.encrypt(password, token);
	        param = "transactionId="+transactionId+"&timestamp="+System.currentTimeMillis()+"&password="+password+"&price="+price+"&contentType="+contentType+"&contentId="+contentId+"&redirectUrl=" + redirectUrl;
            param = AESGenerator.encrypt(param, key);
            // if price = 0, use detect API
            if(price.equals("0"))
            	link = prop.getProperty("DETECTURL");
            // if price > 0, use charge API
            else
            	link = prop.getProperty("CHARGEURL");
            link = link + "?cpId="+cpId+"&param="+param;
            
            log.debug(link);
            return link;
		} catch (Exception e) {
			log.error("Error", e);
			return null;
		}
	}
}
